import { useState } from "react";
import {
  Alert,
  Button,
  Checkbox,
  Form,
  Input,
  Layout,
  message,
  Tabs,
} from "antd";
import { LockOutlined, MobileOutlined, UserOutlined } from "@ant-design/icons";
import { userLogin } from "../../api/userController";

const { Footer } = Layout;

const Login = () => {
  const [form] = Form.useForm();
  const [type, setType] = useState("account");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [captchaSent, setCaptchaSent] = useState(false);
  const [captchaCount, setCaptchaCount] = useState(60);

  // 发送验证码（假数据）
  const handleSendCaptcha = () => {
    setCaptchaSent(true);
    setCaptchaCount(60);
    message.success("验证码已发送，验证码为：1234");
    const timer = setInterval(() => {
      setCaptchaCount((count) => {
        if (count <= 1) {
          clearInterval(timer);
          setCaptchaSent(false);
          return 60;
        }
        return count - 1;
      });
    }, 1000);
  };

  // 登录提交
  const onFinish = async (values: any) => {
    setError("");
    setLoading(true);
    try {
      let params;
      if (type === "account") {
        params = {
          userAccount: values.userAccount,
          userPassword: values.userPassword,
        };
      } else {
        // 手机号登录用手机号和验证码模拟
        if (values.captcha !== "1234") {
          setError("验证码错误");
          setLoading(false);
          return;
        }
        params = {
          userAccount: values.mobile,
          userPassword: values.captcha, // 这里仅做演示，实际应为后端手机号验证码登录接口
        };
      }
      const res = await userLogin(params);
      const result = res.data;
      if (result && result.code === 0 && result.data) {
        if (result.data.token) {
          localStorage.setItem("token", result.data.token);
          console.log("登录成功，token:", result.data.token);
        }
        message.success("登录成功！");
        window.location.href = "/doc";
      } else {
        setError(result?.msg || "登录失败，请重试！");
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      setError("登录失败，请重试！");
    }
    setLoading(false);
  };

  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        background: "linear-gradient(120deg, #f6fafd 0%, #f0f5ff 100%)",
      }}
    >
      <div
        style={{
          margin: "60px auto 0",
          width: 350,
          background: "#fff",
          borderRadius: 8,
          boxShadow: "0 8px 24px #eee",
          padding: 32,
        }}
      >
        <div style={{ textAlign: "center", marginBottom: 24 }}>
          <img src="/vite.svg" alt="logo" style={{ width: 48, height: 48 }} />
          <div style={{ fontSize: 24, fontWeight: 700, marginTop: 8 }}>
            AI 知识库
          </div>
          <div style={{ color: "#888", marginTop: 4 }}>
            打造个人专属的AI知识库
          </div>
        </div>
        <Tabs
          activeKey={type}
          onChange={setType}
          centered
          items={[
            { key: "account", label: "账户密码登录" },
            { key: "mobile", label: "手机号登录" },
          ]}
        />
        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          initialValues={{ autoLogin: true }}
        >
          {type === "account" && (
            <>
              <Form.Item
                name="userAccount"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input
                  size="large"
                  prefix={<UserOutlined />}
                  placeholder="用户名"
                />
              </Form.Item>
              <Form.Item
                name="userPassword"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  size="large"
                  prefix={<LockOutlined />}
                  placeholder="密码"
                />
              </Form.Item>
            </>
          )}
          {type === "mobile" && (
            <>
              <Form.Item
                name="mobile"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1\d{10}$/, message: "手机号格式错误" },
                ]}
              >
                <Input
                  size="large"
                  prefix={<MobileOutlined />}
                  placeholder="手机号"
                />
              </Form.Item>
              <Form.Item
                name="captcha"
                rules={[{ required: true, message: "请输入验证码" }]}
              >
                <Input
                  size="large"
                  prefix={<LockOutlined />}
                  placeholder="验证码"
                  addonAfter={
                    <Button
                      size="small"
                      disabled={captchaSent}
                      onClick={handleSendCaptcha}
                    >
                      {captchaSent ? `${captchaCount}秒后重试` : "获取验证码"}
                    </Button>
                  }
                />
              </Form.Item>
            </>
          )}
          <Form.Item
            name="autoLogin"
            valuePropName="checked"
            style={{ marginBottom: 8 }}
          >
            <Checkbox>自动登录</Checkbox>
          </Form.Item>
          <Form.Item style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Footer style={{ textAlign: "center", background: "none" }}>
        author:weijian
      </Footer>
    </div>
  );
};

export default Login;
